package com.longe.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
@RequestMapping("cookie")
public class TestController {

    @RequestMapping("add")
    public String addCookie(HttpServletResponse response){

        Cookie cookie1 = new Cookie("cookieOne", "保存在硬盘中的cookie");
        cookie1.setMaxAge(300);
        response.addCookie(cookie1);

        Cookie cookie2 = new Cookie("cookieTwo", "保存在浏览器进程中的cookie");
        response.addCookie(cookie2);

        return "check-cookie";
    }

    @RequestMapping("check")
    public String checkCookie(HttpServletRequest request, Map<String, String> map){

        Cookie[] cookies = request.getCookies();
        if(null != cookies){
            for (Cookie cookie : cookies) {
                if(null != cookie && cookie.getName().equals("cookieOne")){
                    map.put("cookieOne", cookie.getValue());
                }
                if(null != cookie && cookie.getName().equals("cookieTwo")){
                    map.put("cookieTwo", cookie.getValue());
                }
            }
        }

        return "test-cookie";
    }
}
